package cn.edu.xaut.mybatisers.mall.ServiceImp;

import cn.edu.xaut.mybatisers.mall.Dao.LoginDao;
import cn.edu.xaut.mybatisers.mall.Entity.Consumer;
import cn.edu.xaut.mybatisers.mall.Exception.ExceptionEntity.LoginException;
import cn.edu.xaut.mybatisers.mall.Service.LoginService;
import cn.edu.xaut.mybatisers.mall.tool.LoginStatus;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@Service
@SuppressWarnings("all")
public class LoginServiceImp implements LoginService {

    @Autowired
    LoginDao loginDao;
    @Autowired
    LoginStatus loginStatus;

    @ApiOperation("处理登录账号密码检查的逻辑")
    @Override
    public Consumer Login(Consumer consumer, String verifyCode, HttpServletResponse response, HttpSession session) throws LoginException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, SQLException {
        if(false){
            System.out.println(session.getAttribute("dueTime"));
            if (session.getAttribute("dueTime") == null || LocalDateTime.parse(String.valueOf(session.getAttribute("dueTime")), DateTimeFormatter.ofPattern("yyyyMMddHHmm")).isBefore(LocalDateTime.now())){
                throw new LoginException("验证码失效");
            }
            if (!verifyCode.equals(session.getAttribute("verifyCode")) || session.getAttribute("verifyCode") == null){
                throw new LoginException("验证码错误");
            }else {
                session.removeAttribute("verifyCode");
            }
        }
        final ArrayList<Consumer> consumers = loginDao.login(consumer);
        if (consumers.size()>0){
            if (consumers.get(0).getPassword().equals(consumer.getPassword())){
                // 给response里面设置登录态
                String token = loginStatus.generateLoginStatus(consumers.get(0).getId());
                System.out.println(token);
                response.setHeader("token", token);
                response.setHeader("consumer_id", String.valueOf(consumers.get(0).getId()));
                session.setAttribute("consumer_id", consumers.get(0).getId());
                if (consumers.get(0).getMember())
                    session.setAttribute("isMember", "1");
                return consumers.get(0);
            }else {
                throw new LoginException("密码错误");
            }
        }else {
            throw new LoginException("账号错误");
        }
    }
}
